function [beta,resid,sigma,G]=ols_ar_vec(yd,pvec,flag_c); 
% ================================================== 
% OLS_AR_VEC.M 
% function [beta,resid,sigma,G]=ols_ar(yd,pvec,flag_c,); 
% 
% OLS  when yd is univariate 
% PVEC is VECTOR which lags to use
% FLAG_C == 0  No constant 
%        === 1 Mean 
% G      companion form matrix 
% 
% BETA  is a row vector
% SIGMA is the standard deviation
% 
% Alejandro Justiniano Feb 11 2006
% ===================================================
yd = yd(:); 
pvec = sort( pvec(:) ); 
dimp = pvec(end); 

xd = lagmat( yd(:) , dimp ); 
yd = xd(dimp+1:end,1); 
xd = xd(dimp+1:end,2:end); 
xd = xd( : , pvec ); 
if flag_c == 1 
    xd = [xd ones( size(xd,1) ,1) ]; 
end 

k = size( xd , 2 ); 
q=(xd'*xd);
q=q\eye(k);
beta=q*xd'*yd;
resid=yd-xd*beta;
sigma=std(resid);
beta=beta';

G= zeros( dimp ); 
if flag_c == 1 ; 
    G(1,pvec)=beta(1:end-1); 
else 
    G(1,pvec)=beta; 
end 
G(2:end,1:end-1) = eye( pvec(end)-1 ); 